package cn.itcast.crm.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 基于map的缓存工具类
 * @author xukuppeng
 */
public class CacheUtils {
 
    //存放缓存的集合
    private final static Map<String, CacheData> cacheDatas = new ConcurrentHashMap<>();
 
    //定时器线程池，用于消除过期缓存
    private final static ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(5);
 
    private final static CacheUtils singleton1 = new CacheUtils();
    
    // 11111111111xkp
    // 11111111111xkp2
    // 以自己实例为返回值的静态的公有方法，静态工厂方法
    public static CacheUtils getCacheUtils(){
        return singleton1;
    }
    /**
     * 1 获取缓存数据
     * @param key
     * @param <T>
     * @return
     */
    public synchronized <T> T get(String key){
        CacheData cacheData = cacheDatas.get(key);
        return cacheData == null ? null : (T) cacheData.data;
    }
 
    //2 设置
 
    /**
     * 设置缓存 永不失效
     * @param key
     * @param value
     */
    public synchronized void put(String key, Object value){
        this.put(key, value, -1L);
    }
 
    /**
     * 设置缓存，需要设置超时时间
     * @param key
     * @param value
     * @param expire    时间单位：毫秒，-1表示永不超时
     */
    public synchronized void put(String key, Object value, Long expire){
        //清除原数据
        cacheDatas.remove(key);
        if(expire > 0){     //大于0才设置
            EXECUTOR.schedule(new Runnable() {
                @Override
                public void run() {
                    //过期后清除缓存
                    synchronized (this){
                        cacheDatas.remove(key);
                    }
                }
            }, expire, TimeUnit.MILLISECONDS);
            cacheDatas.put(key, new CacheData(value, expire));
        }else {
            cacheDatas.put(key, new CacheData(value, -1L));
        }
 
    }
 
    /**
     * 3 删除
     * @param key
     * @param <T>
     * @return
     */
    public synchronized <T> T remove(String key){
        CacheData cacheData = cacheDatas.remove(key);
        return cacheData == null ? null : (T) cacheData.data;
    }
 
    /**
     * 4 总数
     * @return
     */
    public synchronized int size(){
        return cacheDatas.size();
    }
 
    /**
     * 缓存实体类
     */
    public class CacheData{
        //缓存数据
        public  Object data;
        //失效时间
        public Long expire;
 
        public CacheData(Object data, Long expire) {
            this.data = data;
            this.expire = expire;
        }
    }
}
